{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1f20875-c50d-46df-906b-49ec1d0c6002",
   "metadata": {},
   "source": [
    "# 6.3 计算模型的准确率"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "\n",
    "假设有4个样本，对应的标签分别是0,0,1,1。样本使用逻辑回归计算的预测值分别为0.1,0.2,0.8,0.49。\n",
    "\n",
    "要求：\n",
    "- 计算在阈值为0.5的情况下的准确率。\n",
    "- 计算在阈值为0.4的情况下的准确率。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5b4fc39-cbcf-432a-bf1e-e75e642d4b87",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b624ebee-980f-4c1e-b963-a24ff0b669f6",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "使用tf.where方法对预测值进行标签分类后，接着使用tf.equal方法计算预测标签值与样本标签值的异同，最后根据准确率公式计算出模型预测的准确率。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当阈值为0.5时的准确率为： 0.75\n",
      "当阈值为0.4时的准确率为： 1.0\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "# 样本标签\n",
    "y=tf.constant([0,0,1,1],dtype=tf.float32)\n",
    "# 样本预测值\n",
    "pred=tf.constant([0.1,0.2,0.8,0.49],dtype=tf.float32)\n",
    "# 1，在阈值为0.5的情况下求准确率\n",
    "# 由于阈值设置成0.5，所以可以使用tf.round方法对预测值进行四舍五入操作\n",
    "pred1=tf.round(pred)\n",
    "is_equal1= tf.equal(pred1,y)\n",
    "is_equal1=tf.cast(is_equal1,tf.float32)\n",
    "acc1=tf.reduce_mean(is_equal1)\n",
    "print(\"当阈值为0.5时的准确率为：\",acc1.numpy())\n",
    "\n",
    "# 2，在阈值为0.4的情况下求准确率\n",
    "\n",
    "pred2=tf.where(pred<0.4,0,1)\n",
    "pred2=tf.cast(pred2,dtype=tf.float32)\n",
    "is_equal2= tf.equal(pred2,y)\n",
    "# 把布尔型转换成数值型\n",
    "is_equal2=tf.cast(is_equal2,dtype=tf.float32)\n",
    "# 计算准确率\n",
    "acc2=tf.reduce_mean(is_equal2)\n",
    "\n",
    "print(\"当阈值为0.4时的准确率为：\",acc2.numpy())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "947bd149-004c-4238-863f-ba125a57b79b",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
